package com.water.devtool.ui;

import java.util.Map;
import java.util.Set;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.water.devtool.define.ClassBean;
import com.water.devtool.define.EntityBean;
import com.water.devtool.service.CodeGenerateService;

public class CodePreviewDialog extends Dialog {
	final static Logger log = LoggerFactory.getLogger(CodePreviewDialog.class);

	private EntityBean entity;

	protected Object result;
	protected Shell shell;
	private TabFolder tabFolder;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public CodePreviewDialog(Shell parent, int style) {
		super(parent, style);
		setText("SWT Dialog");
	}

	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public Object open() {
		shell.open();
		shell.layout();
		Display display = getParent().getDisplay();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), getStyle());
		Rectangle area = Display.getDefault().getClientArea();
		shell.setSize(area.width, area.height);
		shell.setLocation(0, 0); 
		shell.setText(getText());
		shell.setLayout(new FillLayout(SWT.HORIZONTAL));

		tabFolder = new TabFolder(shell, SWT.NONE);

	}

	public void setEntity(EntityBean entity) {
		createContents();
		this.entity = entity;
		Map<String, ClassBean> classConfig = entity.getClassConfig();
		if (classConfig == null || classConfig.size() == 0) {
			log.debug("不需要生成类");
			return;
		}
		CodeGenerateService service = new CodeGenerateService();
		
		try {
			Map<String, String> codes = service.generateForMap(entity);
			Set<String> keys = classConfig.keySet();
			for (String key : keys) {
				TabItem tabItem = new TabItem(tabFolder, SWT.SHELL_TRIM);
				tabItem.setText(key);
				CodePreviewComposite cc = new CodePreviewComposite(tabFolder, SWT.NONE);
				String str = codes.get(key);
				cc.setContent(str);
				tabItem.setControl(cc);
			}
		} catch (Exception e) {
			e.printStackTrace();
			MessageDialog.openInformation(shell, "错误", e.getMessage());
		}
		

	}
}
